<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="项目名称">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_name"
                placeholder="输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="整改区域">
              <el-select filterable @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.rectification_area" placeholder="选择整改区域">
                <el-option label="前区" :value="1"></el-option>
                <el-option label="后区" :value="2"></el-option>
                <el-option label="仓库" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="整改类型">
              <el-select filterable @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.rectification_type" placeholder="选择整改类型">
                <el-option label="水电" :value="1"></el-option>
                <el-option label="吊顶" :value="2"></el-option>
                <el-option label="门头" :value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目编号">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.project_number"
                placeholder="输入项目编号"></el-input>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="是否影响开业">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.is_affect_opening" placeholder="选择是否影响开业">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="限期整改时间">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.deadline_rectification" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="整改结果">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.rectification_status" placeholder="选择整改结果">
                  <el-option label="待整改" :value="10"></el-option>
                  <el-option label="审核中" :value="20"></el-option>
                  <el-option label="未完成" :value="40"></el-option>
                  <el-option label="已完成" :value="30"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="整改完成时间">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.completion_at" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button type="primary" @click="addRectificationFormFunc"
            v-if="$isPer(permission, ['rectificationForm_add'])">发起整改单</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <div class="tab-box">
          <el-tabs v-model="formSearch.to_do" @tab-click="onSearch(1)">
            <el-tab-pane label="全部" name="0"></el-tab-pane>
            <el-tab-pane label="待处理" name="1"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="list-top-box-right">
          <p class="list-top-box-left">
            已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
          </p>
          <el-button type="primary" @click="exportVisible = true" :disabled="tableData.length == 0"
            v-if="$isPer(permission, ['export_rectificationForm'])">导出整改单列表</el-button>
          <el-button type="primary" :disabled="SCchange" @click="SCchangeFunc"
            v-if="$isPer(permission, ['rectificationForm_submit'])">上传整改内容</el-button>
          <el-button :disabled="SHchange" v-if="$isPer(permission, ['rectificationForm_examine'])"
            style="margin-left: 15px;" type="primary" @click="shZgdFunc">审核整改单</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="pageLoading">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData"
          @selection-change="handleSelectionChange" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="150px" prop="" label="ID">
            <template slot-scope="scope">
              <el-button v-if="$isPer(permission, ['rectificationForm_detail'])" type="text"
                @click="goToDetail(scope.row)">{{ $assemblyListNo('GCZGD', scope.row.id) }}</el-button>
              <span v-else>{{ $assemblyListNo('GCZGD', scope.row.id) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_xmmc')" min-width="180px" prop="project_name" label="项目名称"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_xmbh')" min-width="130px" prop="project_number" label="项目编号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_ysjd')" min-width="130px" prop="node_name" label="验收节点"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.node_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_zgqy')" min-width="100px" prop="rectification_area" label="整改区域"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.rectification_area == 1">前区</span>
              <span v-if="scope.row.rectification_area == 2">后区</span>
              <span v-if="scope.row.rectification_area == 3">仓库</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_zglx')" min-width="100px" prop="rectification_type" label="整改类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.rectification_type == 1">水电</span>
              <span v-if="scope.row.rectification_type == 2">吊顶</span>
              <span v-if="scope.row.rectification_type == 3">门头</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_zgnr')" min-width="180px" prop="rectification_content" label="整改内容"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_tp')" min-width="180px" prop="pending_rectification_files"
            label="图片" show-overflow-tooltip>
            <template slot-scope="scope">
              <div class="img-list-box">
                <el-image class="img-box" v-for="(item, index) in scope.row.pending_rectification_files" :key="index"
                  :src="$fileImgFunc(item)" @click="$fileViewHandle(item)">
                </el-image>
              </div>
              <span v-if="!scope.row.pending_rectification_files.length">--</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_sfyxky')" min-width="110px" prop="is_affect_opening" label="是否影响开业"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.is_affect_opening == 1">是</span>
              <span v-if="scope.row.is_affect_opening == 2">否</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_xqzgsj')" min-width="120px" prop="deadline_rectification"
            label="限期整改时间" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.deadline_rectification || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_zgjg')" min-width="100px" prop="rectification_status" label="整改结果"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.rectification_status == 10">待整改</span>
              <span v-if="scope.row.rectification_status == 20">审核中</span>
              <span v-if="scope.row.rectification_status == 30">已完成</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zgd_zgwcsj')" min-width="120px" prop="completion_at" label="整改完成时间"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.completion_at || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 导出整改单列表 -->
    <el-dialog :modal-append-to-body="false" title="导出整改单字段选择" :visible.sync="exportVisible" width="680px"
      :before-close="exportCloseFunc">
      <el-checkbox class="checkbox-item" v-model="allChecked" @change="allCheckedChangeFunc">全选</el-checkbox>
      <div v-loading="exportLoading">
        <div class="export-scroll">
          <el-checkbox-group v-model="exportrVal">
            <el-checkbox class="checkbox-item" v-for="(item, index) in exportArr" :key="index" :label="item.label"
              border></el-checkbox>
          </el-checkbox-group>
        </div>
        <p v-if="exportUrl">导出文件链接：<el-button @click="$openUrlFunc(exportUrl[0])" type="text">{{
          exportUrl[1]
        }}</el-button></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSubmitFunc">提交</el-button>
        <el-button @click="exportCloseFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import rectificationApi from "@/api/rectificationApi";
import { getUserInfo } from "@/utils/auth";
import { exportRectificationFideldArr } from '@/utils/exportField'
export default {
  name: "rectificationForm",
  components: {},
  data() {
    return {
      // 导出用户列表
      allChecked: false,//是否全选字段
      exportLoading: false,//导出loading
      exportVisible: false,//导出弹窗
      exportUrl: '',//导出url
      exportrVal: [],//导出勾选字段
      exportArr: exportRectificationFideldArr,//导出字段数组

      userInfo: "",
      tableData: [],
      formSearch: {
        to_do: '0',
      },
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      pageLoading: false,
      multipleSelection: [],
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
    // 上传整改内容&& this.userInfo.position_id == 7
    SCchange() {
      if (this.multipleSelection.length == 1 && this.multipleSelection[0].rectification_status == 10) {
        return false;
      } else {
        return true;
      }
    },
    // 审核整改单 && this.userInfo.position_id == 8
    SHchange() {
      if (this.multipleSelection.length == 1 && this.multipleSelection[0].rectification_status == 20) {
        return false;
      } else {
        return true;
      }
    }
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.hrefQueryFunc(() => {
      this.onSearch();
    })
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.hrefQueryFunc(() => {
      this.getRectificationList();//整改单列表
    })
    this.userInfo = getUserInfo();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 跳转判断的
    hrefQueryFunc(cb) {
      let query = this.$route.query;
      if (JSON.stringify(query) != "{}") {
        this.formSearch.project_name = query.project_name || '';//筛选项目名
        this.formSearch.rectification_status = query.rectification_status || '';//整改结果
        this.formSearch.to_do = query.to_do || '0';//是否待处理
      }
      cb && cb();
    },
    // 导出列表确认
    exportSubmitFunc() {
      let exportrVal = this.exportrVal;//已勾选
      let exportArr = this.exportArr;//所有字段
      let formSearch = this.formSearch;//列表筛选项
      if (!exportrVal.length) {
        this.$message({
          type: 'warning',
          message: "请勾选需要导出的字段"
        })
        return;
      }
      let field_list = [];//提交列表
      exportrVal.forEach(item => {
        let index = exportArr.findIndex(child => {
          return item == child.label;
        })
        if (index != -1) {
          field_list.push(exportArr[index].value);
        }
      })
      this.exportRectificationExcel({
        field_list,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        rectification_area: formSearch.rectification_area || '',
        rectification_type: formSearch.rectification_type || '',
        is_affect_opening: formSearch.is_affect_opening || '',
        rectification_status: formSearch.rectification_status || '',
        deadline_rectification_start: formSearch.deadline_rectification ? formSearch.deadline_rectification[0] : '',
        deadline_rectification_end: formSearch.deadline_rectification ? formSearch.deadline_rectification[1] : '',
        completion_at_start: formSearch.completion_at ? formSearch.completion_at[0] : '',
        completion_at_end: formSearch.completion_at ? formSearch.completion_at[1] : '',
      })
    },
    exportRectificationExcel(obj) {
      this.exportUrl = true;
      rectificationApi.exportRectificationExcel(obj).then(res => {
        console.log(res, "导出整改单列表")
        this.exportLoading = false;
        if (res.code == 200) {
          this.exportUrl = res.data;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 导出字段全选
    allCheckedChangeFunc(e) {
      let exportrVal = [];
      console.log(e)
      let exportArr = this.exportArr;
      if (e) {
        exportArr.forEach(item => {
          exportrVal.push(item.label);
        })
        this.exportrVal = exportrVal//已选择字段
      } else {
        this.exportrVal = exportrVal//已选择字段
      }
    },
    // 关闭导出弹窗
    exportCloseFunc() {
      this.exportVisible = false;
      this.allChecked = false;
      this.exportrVal = [];
      this.exportUrl = '';
    },
    // 提交整改内容
    SCchangeFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/rectificationFormDetailPage',
        query: {
          id: this.multipleSelection[0].id,
          submit: true,
        }
      })
    },
    // 发起整改单
    addRectificationFormFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: '/addRectificationForm'
      })
    },
    // 整改单列表
    getRectificationList() {
      this.pageLoading = true;
      let formSearch = this.formSearch;
      rectificationApi.getRectificationList({
        page: this.page,
        num: this.num,
        to_do: formSearch.to_do || 0,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        rectification_area: formSearch.rectification_area || '',
        rectification_type: formSearch.rectification_type || '',
        is_affect_opening: formSearch.is_affect_opening || '',
        rectification_status: formSearch.rectification_status || '',
        deadline_rectification_start: formSearch.deadline_rectification ? formSearch.deadline_rectification[0] : '',
        deadline_rectification_end: formSearch.deadline_rectification ? formSearch.deadline_rectification[1] : '',
        completion_at_start: formSearch.completion_at ? formSearch.completion_at[0] : '',
        completion_at_end: formSearch.completion_at ? formSearch.completion_at[1] : '',
      }).then(res => {
        this.pageLoading = false;
        console.log(res, "整改单列表")
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // table单行点击
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getRectificationList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    goToDetail(row) {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/rectificationFormDetailPage?id=" + row.id
      })
    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // 审核整改单
    shZgdFunc() {
      this.$router.push({
        path: '/rectificationFormDetailPage',
        query: {
          id: this.multipleSelection[0].id,
          examine: true
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>